import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Button, Card, Col, Row, Spin } from 'antd';
import { Ref, useContext, useEffect, useMemo, useRef } from 'react';
import { AnnounceManageAPI } from '../common/type';
import { DoubleRightOutlined, DoubleLeftOutlined } from '@ant-design/icons';
import { AnnounceUpdateContext } from '../common/UpdateContext';
import { ReceiveDeptModalLeft } from './ReceiveDeptModalLeft';
import { getFlowOrgTreeByOrgIDService } from '../service';
import { getPosIDs, loopArray } from '@/utils';
import { ReceiveDeptModalRight } from './ReceiveDeptModalRight';
import { IActionEnum } from '../common/UpdateReducer';

export const ReceiveDeptModal: React.FC<AnnounceManageAPI.IReceiveDeptModal> = ({
  onClose,
}) => {
  const { prefixCls, dispatch, leftSelectRows } = useContext(
    AnnounceUpdateContext,
  );

  const receiveDeptRef: Ref<IOneModalRef> = useRef(null); //弹框的ref

  /* 关闭弹窗 */
  const onCloseModal = () => {
    if (receiveDeptRef) {
      if (receiveDeptRef.current) {
        if (receiveDeptRef.current.onModalCancel) {
          receiveDeptRef.current.onModalCancel();
        }
      }
    }
  };

  const {
    getFlowOrgList,
    getFlowOrgTreeLoading,
    getFlowOrgTreeRun,
  } = getFlowOrgTreeByOrgIDService();

  useEffect(() => {
    let deptParams = {
      params: 1,
      flowType: 1,
      orgID: getPosIDs(),
    };
    getFlowOrgTreeRun(deptParams);
  }, []);

  /**
   * 处理返回 部门数据
   */
  const treeDept = useMemo(() => {
    let loopTree: any = (treeData: any[]) => {
      return treeData
        ?.map((item: any) => {
          if (item?.textType == '1') {
            return {
              ...item,
              children:
                item?.children && item?.children?.length > 0
                  ? loopTree(item?.children)
                  : null,
            };
          } else {
            return undefined;
          }
        })
        ?.filter((item: any) => item && JSON?.stringify(item) != '{}');
    };
    return loopTree(getFlowOrgList);
  }, [getFlowOrgList]);

  /**
   * 全选和反选
   * @param onType 是否全选
   */
  const selectReverseAll = (onType: string) => {
    if (onType == 'AllKey') {
      let checkIDs: any[] = [];
      let checkRows: any[] = [];
      let loop = (dataList: any[]) => {
        dataList?.forEach((item: any) => {
          if (item?.children && item?.children?.length > 0) {
            loop(item?.children);
          }
          if (item?.open == true) {
            checkIDs?.push(item?.id);
            checkRows?.push({ ...item });
          }
        });
      };
      loop(treeDept);
      dispatch({
        type: IActionEnum.LEFTSELECT_KEYS,
        payload: checkIDs,
      });
      dispatch({
        type: IActionEnum.LEFTSELECT_ROW,
        payload: checkRows,
      });
    }
    if (onType == 'delAllKey') {
      dispatch({
        type: IActionEnum.LEFTSELECT_KEYS,
        payload: [],
      });
      dispatch({
        type: IActionEnum.LEFTSELECT_ROW,
        payload: [],
      });
    }
  };

  /**
   *  左侧可以选择的数据数字
   * @returns
   */
  const leftOkCheckLength = () => {
    let nodeList = loopArray(treeDept);
    let onCheckList = nodeList?.filter((item: any) => {
      return item?.open == true;
    });
    return onCheckList?.length;
  };

  /**
   * 判断可选数据 和已选数据大小
   * @returns
   */
  const handleIsCheck = () => {
    let chekcTrue: number = leftSelectRows?.length;
    let checkFalse: number = leftOkCheckLength();
    if (chekcTrue >= checkFalse) {
      return true;
    } else if (chekcTrue <= checkFalse) {
      return false;
    }
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={receiveDeptRef}
        title={'选择接收部门'}
        width={document.body.clientWidth * 0.5}
        onCancel={onClose}
        className={prefixCls + 'addEditModalStyle'}
        bodyStyle={{
          padding: '5px 0px',
          // height: window.screen.height * 0.5,
        }}
        centered
        onOk={onCloseModal}
      >
        <Spin spinning={getFlowOrgTreeLoading}>
          <Card
            bordered={false}
            style={{ width: '100%' }}
            bodyStyle={{ paddingBottom: 0, paddingTop: 5 }}
          >
            <Row className={prefixCls + 'receiveDeptCol'}>
              <ReceiveDeptModalLeft leftTreeData={treeDept} />

              <Col span={2}>
                <div
                  style={{
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    justifyContent: 'center',
                    height: document.body.clientHeight * 0.4,
                  }}
                >
                  <Button
                    style={{ marginBottom: 10 }}
                    type={handleIsCheck() ? 'dashed' : 'primary'}
                    onClick={() => {
                      selectReverseAll('AllKey');
                    }}
                  >
                    <DoubleRightOutlined />
                  </Button>
                  <Button
                    type={handleIsCheck() ? 'primary' : 'dashed'}
                    onClick={() => {
                      selectReverseAll('delAllKey');
                    }}
                  >
                    <DoubleLeftOutlined />
                  </Button>
                </div>
              </Col>

              <ReceiveDeptModalRight leftCheckLength={leftOkCheckLength()} />
            </Row>
          </Card>
        </Spin>
      </OneModal>
    </>
  );
};
